<template>
  <div>
    <div v-if="picture !== ''" class="demo-upload-list">
      <img :src="picture" />
      <div class="demo-upload-list-cover">
        <Icon type="ios-eye-outline" @click.native="handleView"></Icon>
        <Icon type="ios-trash-outline" @click.native="handleRemove"></Icon>
      </div>
    </div>
    <Upload
      v-else
      :show-upload-list="false"
      :format="['jpg','jpeg','png']"
      :max-size="2048"
      :on-format-error="handleFormatError"
      :on-exceeded-size="handleMaxSize"
      :before-upload="handleBeforeUpload"
      action="/posts/"
      style="display: inline-block;width:58px;"
    >
      <div style="width: 58px;height:58px;line-height: 58px;">
        <Icon type="ios-camera" size="20"></Icon>
      </div>
    </Upload>
    <Modal title="View Image" v-model="visible">
      <img :src="picture" v-if="visible" style="width: 100%" />
    </Modal>
  </div>
</template>
<script>
export default {
  name: 'upload-image',
  data() {
    return {
      picture: this.value || '',
      imgName: '',
      visible: false,
      uploadList: [],
    }
  },
  props: {
    value: {
      type: String,
      default: '',
    },
  },
  methods: {
    handleView() {
      this.visible = true
    },
    handleRemove() {
      this.picture = ''
      this.$emit('input', this.picture)
    },
    handleFormatError(file) {
      this.$Notice.warning({
        title: 'The file format is incorrect',
        desc:
          'File format of ' +
          file.name +
          ' is incorrect, please select jpg or png.',
      })
    },
    handleMaxSize(file) {
      this.$Notice.warning({
        title: 'Exceeding file size limit',
        desc: 'File  ' + file.name + ' is too large, no more than 2M.',
      })
    },
    handleBeforeUpload(file) {
      let fileReader = new FileReader()
      let THIS = this
      fileReader.onload = function (e) {
        THIS.$emit('input', e.target.result)
      }
      fileReader.readAsDataURL(file)
      return false
    },
  },
  mounted() {},
  watch: {
    value: function (newValue) {
      this.picture = newValue || ''
    },
  },
}
</script>
<style>
.demo-upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}
.demo-upload-list img {
  width: 100%;
  height: 100%;
}
.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}
.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
</style>
